import React, { Component } from 'react';// 各种包一定要注意导入
import {
    StyleSheet,
    Text,
    View,
    TouchableOpacity,
    Image,
    FlatList,
    ActivityIndicator,
    NativeModules,
    ScrollView
} from 'react-native';

import { NavigationBar, Toast, Theme, SearchInput } from 'teaset'

const Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

let pageNo = 1;//当前第几页
let totalPage = 5;//总的页数
let itemNo = 0;//item的个数

import { getArtPage, getCategoryTree } from '../Api/BookApi'

var customKey = null;
var that;

var _subScrollView = null;
var _scrollView = null;

export default class SearchCategoryList extends Component {
    constructor(props) {

        super(props);

        that = this;

        this.params = {
            subCategoryId: global.searchSubCategoryId||0,
            categoryShowBack:global.categoryShowBack||''
        }

        this.state = {
            isLoading: false,
            error: false,
            errorInfo: "",
            dataArray: [],
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            isRefreshing: false,//下拉控制
            ListDataLoading: true,
            searchKeyWord: "",

            subCategoryId: 0,


            activeIndex: 0,
            activeSubIndex: 0,
            activeCategoryId: 0,
            activeSubCategoryId: this.params.subCategoryId || 0,
            categoryTree: [],
            showCategoryArr: [],
            showSubCategoryArr: []
        }
    }

    //网络请求——获取第pageNo页数据
    fetchData(pageNo) {

        var that = this;

        that.showCustom();

        //有子类传子传  没子类传一级   两个都为0 则传null
        var curCategoryId = null;

        console.log(this.state.activeCategoryId, this.state.activeSubCategoryId);

        if (this.state.activeSubCategoryId != 0 || this.state.activeCategoryId != 0) {
            if (this.state.activeSubCategoryId != 0) {
                curCategoryId = this.state.activeSubCategoryId;
            } else {
                curCategoryId = this.state.activeCategoryId;
            }
        }

        //这个是js的访问网络的方法
        getArtPage({
            "pageSize": 20,
            "pageIndex": pageNo + 1,
            "key": null,
            "categoryId": curCategoryId
        })
            .then((responseData) => {
                console.log(responseData, '=========responseData==========');

                let data = responseData.data;
                let dataBlob = [];
                let i = itemNo;

                totalPage = Math.ceil(responseData.total / 10);

                data.map(function (item) {
                    dataBlob.push({
                        key: i,
                        value: item,
                    })
                    i++;
                });

                itemNo = i;
                console.log("itemNo:" + itemNo);
                let foot = 0;
                if (pageNo >= totalPage) {
                    foot = 1;//listView底部显示没有更多数据了
                }

                this.setState({
                    //复制数据源
                    dataArray: this.state.dataArray.concat(dataBlob),
                    isLoading: false,
                    showFoot: foot,
                    isRefreshing: false,
                });
                data = null;
                dataBlob = null;
                that.hideCustom();
            })
            .catch((error) => {
                this.setState({
                    error: true,
                    errorInfo: error
                })
            })
            .done();
    }

    componentDidMount() {
        //请求数据
        this.fetchData(pageNo);

        this.getCategoryTree();
    }


    //加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='red'
                    size="large"
                />
            </View>
        );
    }

    //加载失败view
    renderErrorView() {
        return (
            <View style={styles.container}>
                <Text>
                    加载失败
                </Text>
            </View>
        );
    }

    //返回itemView
    _renderItemView({ item }) {
        console.log(item, '============item=============');
        return (
            <View style={styles.each} key={item.value.book_id} >
                <View style={styles.each_left}>
                    <Image style={styles.each_left_img} source={{ uri: item.value.book_cover }}></Image>
                </View>

                <TouchableOpacity style={styles.each_right} onPress={() => {
                    console.log(item, "============_renderItemView===========")
                    NativeModules.BaseBridge.goToBookDetail('' + item.value.book_id, '' + item.value.book_name);

                }}>
                    <Text style={[styles.each_right_top, styles.each_right_txt, { fontSize: global.ScreenSizeMod > 1 ? 16 : 12 }]}>{item.value.book_name}</Text>
                    <Text style={[styles.each_right_center, styles.each_right_txt, { fontSize: global.ScreenSizeMod > 1 ? 14 : 11 }]} numberOfLines={global.ScreenSizeMod == 1 ? 2 : 3}>
                        {('' + item.value.book_intro).replace(/\s+/g, '')}
                    </Text>
                    <View style={[styles.each_right_bottom, styles.each_right_txt]} numberOfLines={1}>
                        <Text style={[styles.echo_right_bottom_left, { fontSize: global.ScreenSizeMod > 1 ? 13 : 11 }]}>
                            {item.value.book_author}
                        </Text>
                        <Text style={[styles.echo_right_bottom_right, { fontSize: global.ScreenSizeMod > 1 ? 13 : 11 }]}>
                            {item.value.book_class}
                        </Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }

    renderData() {
        var that = this;
        return (

            <View style={[styles.appContainer]}>


            {

                global.categoryShowBack=="1"&&<NavigationBar
                    title={'分类搜索'}
                    statusBarHidden={false}
                    hidden={false}
                    statusBarHidden={false}
                    statusBarInsets={true}
                    style={{ backgroundColor: '#3771B4' }}

                    leftView={
                        <NavigationBar.BackButton title=''
                        onPress={() => {
                            NativeModules.BaseBridge.closeCurrentController();
                        }} />
                    } />
            }
                 {

                global.categoryShowBack!="1"&&<NavigationBar
                    title={'分类搜索'}
                    statusBarHidden={false}
                    hidden={false}
                    statusBarHidden={false}
                    statusBarInsets={true}
                    style={{ backgroundColor: '#3771B4' }} />
            }
                

              

                <View style={{ height: 88, backgroundColor: '#f2f2f2', marginTop: global.isIphoneX ? 88 : 64 }}>
                    <ScrollView style={styles.scrollViewStyle} horizontal={true} showsHorizontalScrollIndicator={false} ref={(scrollView) => { _scrollView = scrollView; }}>
                        {this.renderCategory()}
                    </ScrollView>

                    <ScrollView style={styles.scrollViewStyle} horizontal={true} showsHorizontalScrollIndicator={false} ref={(scrollView) => { _subScrollView = scrollView; }}>
                        {this.renderSubCategory()}
                    </ScrollView>
                </View>


                <View style={{
                    flex: 1
                }}>
                    <FlatList
                        data={this.state.dataArray}
                        renderItem={this._renderItemView}
                        ListFooterComponent={this._renderFooter.bind(this)}
                        onEndReached={this._onEndReached.bind(this)}
                        onEndReachedThreshold={1}
                    />
                </View>
            </View>
        );
    }


    showCustom() {
        if (customKey) return;
        customKey = Toast.show({
            text: <Text style={{ color: '#fff', fontSize: 12 }}>加载中...</Text>,
            icon: <ActivityIndicator color={Theme.toastIconTintColor} />,
            position: 'center',
            duration: 500,
            overlayOpacity: 0.2,
            modal: true
        });
    }

    hideCustom() {
        if (!customKey) return;
        Toast.hide(customKey);
        customKey = null;
    }


    render() {
        //第一次加载等待的view
        if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //请求失败view
            return this.renderErrorView();
        }
        //加载数据
        return this.renderData();
    }


    _renderFooter() {
        if (this.state.showFoot === 1) {
            return (
                <View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
                    <Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5, }}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator animating={true}
                        color='#666' />
                    <Text style={{ color: '#666', fontSize: 12 }}> 正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if ((pageNo != 1) && (pageNo >= totalPage)) {
            return;
        } else {
            pageNo++;
        }
        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });
        //获取数据
        this.fetchData(pageNo);
    }


    //所有数据
    getCategoryTree() {
        var that = this;
        getCategoryTree().then((res) => {

            console.log(res, '=========getCategoryTree=========');
            var subArr = [];
            for (var i = 0; i < res.length; i++) {
                subArr = subArr.concat(res[i].children)
            }
            res.splice(0, 0, {
                "name": "全部",
                "pid": 0,
                "id": 0,
                'children': []
            })

            subArr.splice(0, 0, {
                "name": "全部",
                "pid": 0,
                "id": 0,
                'children': []
            })

            console.log(that.params.subCategoryId, "=======that.params.subCategoryId========");
            console.log(subArr, "============subArr===========");

            var kIndex = 0;
            for (var k = 0; k < subArr.length; k++) {
                if ('' + subArr[k].id == that.params.subCategoryId) {
                    kIndex = k
                }
            }

            console.log(kIndex, "=========kIndex=============")

            this.setState({
                categoryTree: res,
                showCategoryArr: res,
                showSubCategoryArr: subArr,
                activeSubIndex: kIndex
            }, function () {

                setTimeout(() => {
                    // _subScrollView && _subScrollView.scrollToEnd({ animated: true })
                    _subScrollView && _subScrollView.scrollTo({ x: kIndex * 50 > 250 ? kIndex * 50 - 250 : kIndex * 50 });
                }, 0);


            });

        }).catch((error) => {
            this.setState({
                error: true,
                errorInfo: error
            })
        })
            .done();
    }

    renderCategory() {
        var that = this;
        // 数组
        var itemAry = [];
        // 遍历
        for (let i = 0; i < this.state.showCategoryArr.length; i++) {

            itemAry.push(
                <TouchableOpacity
                    onPress={() => {

                        this.showCustom();
                        _subScrollView.scrollTo({ x: 0 });

                        this.setState({
                            activeIndex: i,
                            activeCategoryId: this.state.showCategoryArr[i].id,
                            activeSubIndex: 0,
                            activeSubCategoryId: 0,
                            dataArray: []
                        }, function () {
                            pageNo = 1;
                            this.fetchData(pageNo);
                        });
                    }}
                >
                    <View key={i} style={[styles.itemStyle]}>
                        <Text style={[{ fontSize: global.ScreenSizeMod > 1 ? 15 : 12 }, this.state.activeIndex == i ? styles.activeEachText : styles.eachText]}>{this.state.showCategoryArr[i].name}</Text>
                    </View>
                </TouchableOpacity>

            );

        }
        return itemAry;
    }

    renderSubCategory() {
        var itemAry = [];
        // 遍历
        for (let i = 0; i < this.state.showSubCategoryArr.length; i++) {
            (this.state.activeCategoryId == 0 || this.state.showSubCategoryArr[i].id == 0 || this.state.showSubCategoryArr[i].pid == this.state.activeCategoryId) && itemAry.push(
                <TouchableOpacity
                    onPress={() => {

                        this.showCustom();
                        // _subScrollView.scrollTo({ x: 0 });
                        this.setState({
                            activeSubIndex: i,
                            activeSubCategoryId: this.state.showSubCategoryArr[i].id,
                            dataArray: []
                        }, function () {
                            pageNo = 1;
                            this.fetchData(pageNo);
                        });
                    }}
                >
                    <View key={i} style={[styles.itemStyle]}>
                        <Text style={[{ fontSize: global.ScreenSizeMod > 1 ? 15 : 12 }, this.state.activeSubIndex == i ? styles.activeEachText : styles.eachText]}>{this.state.showSubCategoryArr[i].name}</Text>
                    </View>
                </TouchableOpacity>
            );
        }
        return itemAry;
    }


}

const styles = StyleSheet.create({
    appContainer: {
        flex: 1,
        backgroundColor: '#f2f2f2'
    },
    mainView: {
        flex: 1
    },
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    // title: {
    //     fontSize: 15,
    //     color: 'blue',
    // },
    footer: {
        flexDirection: 'row',
        height: 44,
        justifyContent: 'center',
        alignItems: 'center',
        // marginBottom: 10,
    },
    content: {
        fontSize: 15,
        color: 'black',
    },


    each: {
        flexDirection: 'row',
        marginBottom: 1,
        backgroundColor: '#fff'
    },
    artList: {
        margin: 4
    },
    each_left: {
        width: width / 4,
        height: (width / 4) * 1.3
    },
    each_right: {
        flex: 1,
        flexDirection: 'column',
        padding: 4,
        paddingLeft: 0
    },
    each_right_top: {
        color: '#555',
        lineHeight: 16
    },
    each_right_center: {
        paddingTop: 4,
        paddingRight: 2,
        color: '#999',
        lineHeight: 16
    },
    each_left_img: {
        flex: 1,
        margin: 4
    },
    each_right_bottom: {
        flex: 1,
        flexDirection: "row",
        height: 20,
        color: '#999',
        marginTop: 4,
        // backgroundColor: 'red',
        justifyContent: 'center',
        alignItems: 'center'

    },
    echo_right_bottom_left: {
        flex: 1,
        color: '#999'
    },
    echo_right_bottom_right: {
        flex: 1,
        textAlign: 'right',
        color: '#999'
    },


    scrollViewStyle: {
        height: 44,
        backgroundColor: 'white',
        marginBottom: 1
    },

    itemStyle: {
        width: 40,
        height: 44,
        justifyContent: 'center',
        alignItems: 'center'
    },
    eachText: {
        color: '#666'
    },
    activeEachText: {
        color: '#E04D45'
    }
});